<script setup lang="ts">

import {Dialog} from "@/components/Dialog";
import {studentCheckBox, studentExport} from "@/api/student";

const props = defineProps({
  excelVisible: Boolean,
  student_ids: Array,
  searchItem: Object,
})
const emit = defineEmits(['handleExcelClose'])
import {ref, reactive, onMounted} from "vue";
import {ElMessage} from "element-plus";

const checkAll = ref(true)
let exportLoading = ref(false)
let cities = ref([])
let excelRef = ref('')

let isIndeterminate = ref(true)
const outStudent = () => {


  excelRef.value.validate(async valid => {
    if (valid) {
      let data;
      data = props.searchItem
      data.field = excelExportForm.field
      data.student_ids = props.student_ids
      console.log(data);
      let res = await studentExport(data)
      if (res) {
        window.location.href = res.data
        ElMessage({type: 'success', message: '导出成功'})
        handleExcelCancel()
      }
    }
  })
}
const handleExcelCancel = () => {
  emit('handleExcelClose')
}


let excelExportForm = reactive({
  field: [],
})
const fetchData = async () => {
  let res = await studentCheckBox();
  if (res) {
    cities.value = res.data
    cities.value.forEach((item, index) => {
      excelExportForm.field.push(index)
    })
  }
}

onMounted(() => {
  fetchData()
})

const handleCheckAllChange = (val: boolean) => {
  if (val) {
    excelExportForm.field = []
    cities.value.forEach((item, index) => {
      excelExportForm.field.push(index)
    })
  } else {
    excelExportForm.field = []
  }
  isIndeterminate.value = false
}

const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === cities.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < cities.value.length
}

</script>

<template>
  <Dialog :title="'Excel批量导出'" :model-value="excelVisible" @handle-close="handleExcelCancel" :max-height="'200px'">
    <el-form :model="excelExportForm" ref="excelRef" label-width="110px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="选择导出字段" prop="field"
                        :rules="[{required: true,message: '请选择要导出的字段',trigger: 'change'} ]">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
            </el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="excelExportForm.field" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="(city,index) in cities" :label="index" :key="index">{{ city }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="handleExcelCancel">取 消</el-button>
      <el-button type="primary" @click="outStudent" :loading="exportLoading">确认导出</el-button>
    </template>
  </Dialog>
</template>
